

-- Namespace
	local _,mod = ...


-- Unit resolution
	local units = mod.units
	
	local resolve = {}; mod.resolve = resolve
	local guids = {}
	
	local unit_care = mod:unitevent_care('unit')
	
	local function updateunit(unit)
		local u = units[unit]
		if not u then return end
		
		local changed
		local exists = UnitExists(unit)
		local guid
		if exists then
			guid = UnitGUID(unit)
			if guid and guid ~= guids[unit] then
				guids[unit] = guid
				changed = true
			end
		else
			if guids[unit] then
				guids[unit] = nil
				changed = true
			end
		end
		
		if not changed then return end
		
		-- Throw the unit-changed event
		if unit_care and unit_care[unit] then
			u:Update('unit',exists,guid)
		end
		
		-- Throw the rest
		for i = 1,#resolve do
			resolve[i](unit,exists,guid)
		end
	end
	
	mod:event_register('PLAYER_ENTERING_WORLD',function()
		for unit in pairs(units) do
			updateunit(unit)
		end
	end)
	
	if units['target'] or units['targettarget'] then
		mod:event_register('PLAYER_TARGET_CHANGED',function()
			updateunit('target')
			updateunit('targettarget')
		end)
	end
	
	if units['focus'] or units['focustarget'] then
		mod:event_register('PLAYER_FOCUS_CHANGED',function()
			updateunit('focus')
			updateunit('focustarget')
		end)
	end
	
	mod:event_register('UNIT_TARGET',function(unit)
		if not unit then return end
		unit = unit..'target'
		updateunit(unit)
	end)
	
	mod:event_register('UNIT_PET',function(unit)
		if unit == 'player' then
			unit = 'pet'
		elseif unit then
			unit = unit..'pet'
		else
			return
		end
		updateunit(unit)
	end)
	
	if units['party1'] then
		mod:event_register('GROUP_ROSTER_UPDATE',function()
			local unit
			for i = 1,4 do
				unit = ('party%d'):format(i)
				updateunit(unit)
			end
		end)
	end
	
	if units['arena1'] then
		mod:event_register('ARENA_OPPONENT_UPDATE',function()
			local unit
			for i = 1,5 do
				unit = ('arena%d'):format(i)
				updateunit(unit)
			end
		end)
	end
	
	if units['mouseover'] then
		local function scan_mouseover()
			if not UnitExists('mouseover') then
				updateunit('mouseover')
				mod:timer_unregister(scan_mouseover)
			end
		end
		
		mod:event_register('UPDATE_MOUSEOVER_UNIT',function()
			updateunit('mouseover')
			if UnitExists('mouseover') then
				mod:timer_register(0,true,scan_mouseover)
			end
		end)
	end
